import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'providers/auth_provider.dart';
import 'providers/profile_provider.dart';

/// 🎯 简约风格的个人信息页面 - Flutter + Provider架构
///
/// 功能特点：
/// - ✅ 简约现代的UI设计
/// - ✅ 基于Provider状态管理
/// - ✅ 个人信息增删改操作
/// - ✅ 密码修改功能
/// - ✅ 头像上传(待实现)
/// - ✅ 退出登录功能
class SimpleProfilePage extends StatefulWidget {
  const SimpleProfilePage({super.key});

  @override
  State<SimpleProfilePage> createState() => _SimpleProfilePageState();
}

class _SimpleProfilePageState extends State<SimpleProfilePage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();
  final _bioController = TextEditingController();
  final _phoneController = TextEditingController();
  final _locationController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      final profileProvider = Provider.of<ProfileProvider>(
        context,
        listen: false,
      );

      if (authProvider.user != null) {
        profileProvider.setUser(authProvider.user);
        _initializeControllers(authProvider.user!);
      }
    });
  }

  void _initializeControllers(user) {
    _nameController.text = user.name ?? '';
    _emailController.text = user.email ?? '';
    _bioController.text = user.bio ?? '';
    _phoneController.text = user.phone ?? '';
    _locationController.text = user.location ?? '';
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _bioController.dispose();
    _phoneController.dispose();
    _locationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => ProfileProvider(),
      child: Scaffold(
        backgroundColor: Colors.grey[50],
        body: Consumer<ProfileProvider>(
          builder: (context, profileProvider, child) {
            return CustomScrollView(
              slivers: [
                _buildAppBar(context, profileProvider),
                SliverToBoxAdapter(child: _buildBody(context, profileProvider)),
              ],
            );
          },
        ),
      ),
    );
  }

  /// 🎨 构建应用栏 - 渐变背景 + 头像展示
  Widget _buildAppBar(BuildContext context, ProfileProvider profileProvider) {
    return SliverAppBar(
      expandedHeight: 200,
      floating: false,
      pinned: true,
      backgroundColor: Colors.blue[700],
      foregroundColor: Colors.white,
      iconTheme: const IconThemeData(color: Colors.white),
      automaticallyImplyLeading: true,
      flexibleSpace: FlexibleSpaceBar(
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Colors.blue[700]!, Colors.blue[500]!],
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(height: 40),
              _buildAvatar(profileProvider),
              const SizedBox(height: 16),
              Text(
                profileProvider.user?.name ?? '用户',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                profileProvider.user?.email ?? '',
                style: const TextStyle(color: Colors.white70, fontSize: 16),
              ),
            ],
          ),
        ),
      ),
      actions: [
        if (profileProvider.isEditing)
          TextButton.icon(
            onPressed:
                profileProvider.isLoading
                    ? null
                    : () => _saveProfile(profileProvider),
            icon:
                profileProvider.isLoading
                    ? const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        color: Colors.white,
                      ),
                    )
                    : const Icon(Icons.save, color: Colors.white),
            label: const Text('保存', style: TextStyle(color: Colors.white)),
          )
        else
          IconButton(
            onPressed: profileProvider.toggleEditing,
            icon: const Icon(Icons.edit, color: Colors.white),
            tooltip: '编辑资料',
          ),
      ],
    );
  }

  /// 👤 构建头像 - 带编辑功能
  Widget _buildAvatar(ProfileProvider profileProvider) {
    return Stack(
      children: [
        CircleAvatar(
          radius: 40,
          backgroundColor: Colors.white24,
          backgroundImage:
              profileProvider.user?.avatar != null
                  ? NetworkImage(profileProvider.user!.avatar!)
                  : null,
          child:
              profileProvider.user?.avatar == null
                  ? const Icon(Icons.person, size: 40, color: Colors.white70)
                  : null,
        ),
        if (profileProvider.isEditing)
          Positioned(
            bottom: 0,
            right: 0,
            child: GestureDetector(
              onTap: () => _uploadAvatar(profileProvider),
              child: Container(
                padding: const EdgeInsets.all(4),
                decoration: const BoxDecoration(
                  color: Colors.blue,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.camera_alt,
                  size: 16,
                  color: Colors.white,
                ),
              ),
            ),
          ),
      ],
    );
  }

  /// 📝 构建页面主体内容
  Widget _buildBody(BuildContext context, ProfileProvider profileProvider) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 🚨 错误提示
            if (profileProvider.errorMessage != null) ...[
              _buildErrorCard(profileProvider.errorMessage!),
              const SizedBox(height: 16),
            ],

            // 👤 基本信息区域
            _buildSectionTitle('基本信息', Icons.person_outline),
            const SizedBox(height: 16),
            _buildInfoCard([
              _buildTextField(
                controller: _nameController,
                label: '姓名',
                icon: Icons.person,
                enabled: profileProvider.isEditing,
                validator: (value) => value?.isEmpty == true ? '请输入姓名' : null,
              ),
              const SizedBox(height: 16),
              _buildTextField(
                controller: _emailController,
                label: '邮箱',
                icon: Icons.email,
                enabled: false, // 邮箱不允许修改
                keyboardType: TextInputType.emailAddress,
              ),
              const SizedBox(height: 16),
              _buildTextField(
                controller: _bioController,
                label: '个人简介',
                icon: Icons.info_outline,
                enabled: profileProvider.isEditing,
                maxLines: 3,
                hintText: '介绍一下自己...',
              ),
            ]),

            const SizedBox(height: 24),

            // 📞 联系信息区域
            _buildSectionTitle('联系信息', Icons.contact_phone_outlined),
            const SizedBox(height: 16),
            _buildInfoCard([
              _buildTextField(
                controller: _phoneController,
                label: '手机号码',
                icon: Icons.phone,
                enabled: profileProvider.isEditing,
                keyboardType: TextInputType.phone,
                hintText: '+86 138 0000 0000',
              ),
              const SizedBox(height: 16),
              _buildTextField(
                controller: _locationController,
                label: '所在地区',
                icon: Icons.location_on,
                enabled: profileProvider.isEditing,
                hintText: '北京市海淀区',
              ),
            ]),

            const SizedBox(height: 24),

            // ⚙️ 账户设置区域
            _buildSectionTitle('账户设置', Icons.settings_outlined),
            const SizedBox(height: 16),
            _buildActionCard([
              _buildActionItem(
                icon: Icons.lock_outline,
                title: '修改密码',
                subtitle: '定期更换密码，保护账户安全',
                onTap:
                    () => _showChangePasswordDialog(context, profileProvider),
              ),
              const Divider(height: 1),
              _buildActionItem(
                icon: Icons.logout,
                title: '退出登录',
                subtitle: '安全退出当前账户',
                onTap: () => _showLogoutDialog(context, profileProvider),
                isDestructive: true,
              ),
            ]),

            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }

  /// 🏷️ 构建区域标题
  Widget _buildSectionTitle(String title, IconData icon) {
    return Row(
      children: [
        Icon(icon, color: Colors.blue[700], size: 20),
        const SizedBox(width: 8),
        Text(
          title,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.grey[800],
          ),
        ),
      ],
    );
  }

  /// 📋 构建信息卡片
  Widget _buildInfoCard(List<Widget> children) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(children: children),
    );
  }

  /// 🎭 构建操作卡片
  Widget _buildActionCard(List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(children: children),
    );
  }

  /// ✏️ 构建输入框
  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required IconData icon,
    bool enabled = true,
    int maxLines = 1,
    TextInputType? keyboardType,
    String? hintText,
    String? Function(String?)? validator,
  }) {
    return TextFormField(
      controller: controller,
      enabled: enabled,
      maxLines: maxLines,
      keyboardType: keyboardType,
      validator: validator,
      decoration: InputDecoration(
        labelText: label,
        hintText: hintText,
        prefixIcon: Icon(icon, color: Colors.blue[600]),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: Colors.grey[300]!),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: Colors.grey[300]!),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: Colors.blue[600]!),
        ),
        disabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: BorderSide(color: Colors.grey[200]!),
        ),
        filled: !enabled,
        fillColor: enabled ? null : Colors.grey[50],
      ),
    );
  }

  /// 🎯 构建操作项
  Widget _buildActionItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    bool isDestructive = false,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: isDestructive ? Colors.red[600] : Colors.blue[600],
      ),
      title: Text(
        title,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          color: isDestructive ? Colors.red[600] : null,
        ),
      ),
      subtitle: Text(subtitle),
      trailing: Icon(Icons.chevron_right, color: Colors.grey[400]),
      onTap: onTap,
    );
  }

  /// ⚠️ 构建错误提示卡片
  Widget _buildErrorCard(String message) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.red[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.red[200]!),
      ),
      child: Row(
        children: [
          Icon(Icons.error_outline, color: Colors.red[600]),
          const SizedBox(width: 8),
          Expanded(
            child: Text(message, style: TextStyle(color: Colors.red[700])),
          ),
        ],
      ),
    );
  }

  /// 💾 保存个人信息
  Future<void> _saveProfile(ProfileProvider profileProvider) async {
    if (!_formKey.currentState!.validate()) return;

    final success = await profileProvider.updateProfile(
      name: _nameController.text.trim(),
      email: _emailController.text.trim(),
      bio:
          _bioController.text.trim().isEmpty
              ? null
              : _bioController.text.trim(),
      phone:
          _phoneController.text.trim().isEmpty
              ? null
              : _phoneController.text.trim(),
      location:
          _locationController.text.trim().isEmpty
              ? null
              : _locationController.text.trim(),
    );

    if (mounted) {
      if (success) {
        // 🔥 关键：同步更新AuthProvider中的用户数据
        final authProvider = Provider.of<AuthProvider>(context, listen: false);
        if (profileProvider.user != null) {
          authProvider.updateUserData(profileProvider.user!);
        }

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('个人信息更新成功'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(profileProvider.errorMessage ?? '保存失败'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 📸 上传头像
  Future<void> _uploadAvatar(ProfileProvider profileProvider) async {
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text('头像上传功能开发中...')));
  }

  /// 🔑 显示修改密码对话框
  void _showChangePasswordDialog(
    BuildContext context,
    ProfileProvider profileProvider,
  ) {
    final currentPasswordController = TextEditingController();
    final newPasswordController = TextEditingController();
    final confirmPasswordController = TextEditingController();
    final formKey = GlobalKey<FormState>();

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('修改密码'),
            content: Form(
              key: formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextFormField(
                    controller: currentPasswordController,
                    obscureText: true,
                    decoration: const InputDecoration(
                      labelText: '当前密码',
                      prefixIcon: Icon(Icons.lock_outline),
                    ),
                    validator:
                        (value) => value?.isEmpty == true ? '请输入当前密码' : null,
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: newPasswordController,
                    obscureText: true,
                    decoration: const InputDecoration(
                      labelText: '新密码',
                      prefixIcon: Icon(Icons.lock),
                    ),
                    validator: (value) {
                      if (value?.isEmpty == true) return '请输入新密码';
                      if (value!.length < 6) return '密码长度至少6位';
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: confirmPasswordController,
                    obscureText: true,
                    decoration: const InputDecoration(
                      labelText: '确认新密码',
                      prefixIcon: Icon(Icons.lock_reset),
                    ),
                    validator: (value) {
                      if (value?.isEmpty == true) return '请确认新密码';
                      if (value != newPasswordController.text) {
                        return '两次密码输入不一致';
                      }
                      return null;
                    },
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () async {
                  if (formKey.currentState!.validate()) {
                    Navigator.pop(context);
                    final success = await profileProvider.changePassword(
                      currentPassword: currentPasswordController.text,
                      newPassword: newPasswordController.text,
                    );
                    if (success && mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('密码修改成功'),
                          backgroundColor: Colors.green,
                        ),
                      );
                    }
                  }
                },
                child: const Text('确认'),
              ),
            ],
          ),
    );
  }

  /// 🚪 显示退出确认对话框
  void _showLogoutDialog(
    BuildContext context,
    ProfileProvider profileProvider,
  ) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('确认退出'),
            content: const Text('确定要退出当前账户吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                onPressed: () async {
                  Navigator.pop(context);
                  await profileProvider.logout();
                  if (mounted) {
                    Navigator.pushReplacementNamed(context, '/login');
                  }
                },
                child: const Text('退出'),
              ),
            ],
          ),
    );
  }
}
